package com.fintech.pangu.generator.util;

import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.fintech.pangu.generator.constant.DBConstant;
import com.fintech.pangu.generator.entity.FieldInfomation;
import com.fintech.pangu.generator.entity.TableFieldExtend;
import com.fintech.pangu.generator.entity.TableGeneratorConfig;
import com.fintech.pangu.generator.entity.TableInfomation;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 代码生成工具类
 * @Author xiexiaole
 * @Date 2019/11/15 18:12
 */
public class GeneratorUtil {

    /**
     * @Description: 字段属性扩展
     * @Author xiexiaole
     * @Date 2019/11/16 10:03
     * @param
     * @return
     */
    public static TableFieldExtend convertTable(TableField tableField, TableGeneratorConfig tableConfig){
        TableFieldExtend fieldExtend = new TableFieldExtend(tableField);
        String name = fieldExtend.getName();
        //TODO dto扩展
        Map<String, Integer> dtoGeneratorColumn = tableConfig.getDtoGeneratorColumn();
        Integer dtoGenerator = dtoGeneratorColumn == null ? 1 : dtoGeneratorColumn.get(name);
        fieldExtend.setDtoGenerate(dtoGenerator);
        // TODO VO扩展
        Map<String, Integer> voGeneratorColumn = tableConfig.getVoGeneratorColumn();
        Integer voGenerator = voGeneratorColumn == null ? 0 : voGeneratorColumn.get(name);
        fieldExtend.setVoGenerate(voGenerator);
        // TODO createUpdate 扩展
        Map<String, Integer> cuGeneratorColumn = tableConfig.getCuGeneratorColumn();
        Integer cuGenerator = cuGeneratorColumn == null ? 0 : cuGeneratorColumn.get(name);
        fieldExtend.setCuGenerate(cuGenerator);
        // TODO fetch 扩展
        Map<String, Integer> fetchGeneratorColumn = tableConfig.getFetchGeneratorColumn();
        Integer fetchGenerator = fetchGeneratorColumn == null ? 0 : fetchGeneratorColumn.get(name);
        fieldExtend.setFetchGenerate(fetchGenerator);
        return fieldExtend;
    }
    public static String getDataBase(String url){
        //localhost:8008/getTableList?dbUrl=jdbc:mysql://172.18.101.97:3306/pangumsfdevdb?useUnicode=true%26useSSL=false%26characterEncoding=utf8&userName=pangu_msf_dev&password=pangu_msf_dev
        int start = url.lastIndexOf("/")+1;
        int end = url.indexOf("?");
        if(end <=0){
            String dataBase = url.substring(start);
            return dataBase;
        }else {
            String dataBase = url.substring(start,end);
            return dataBase;
        }
    }

    public static List<TableInfomation> getResult(JDBCUtil instance,ResultSet resultSet,String dataBase) throws SQLException {
        List<TableInfomation> tableInfoList = new ArrayList();
        while(resultSet.next()) {
            String tableName = resultSet.getString("TABLE_NAME");
            String tableType = resultSet.getString("TABLE_TYPE");
            String engine = resultSet.getString("ENGINE");
            String tableCollation = resultSet.getString("TABLE_COLLATION");
            String tableComment = resultSet.getString("TABLE_COMMENT");
            TableInfomation infomation = new TableInfomation();
            infomation.setTableName(tableName);
            infomation.setEngine(engine);
            infomation.setTableCollation(tableCollation);
            infomation.setTableComment(tableComment);
            infomation.setTableType(tableType);
            ResultSet result = instance.executeSQL(DBConstant.SELECT_DB_TABLE_FIELD, dataBase, tableName);
            List<FieldInfomation> fields=new ArrayList<>();
            while (result.next()) {
                FieldInfomation infomation1 = new FieldInfomation();
                infomation1.setColumnName(result.getString("COLUMN_NAME"));
                infomation1.setColumnDefault(result.getString("COLUMN_DEFAULT"));
                infomation1.setIsNullable(result.getString("IS_NULLABLE"));
                infomation1.setDataType(result.getString("DATA_TYPE"));
                infomation1.setColumnType(result.getString("COLUMN_TYPE"));
                infomation1.setColumnKey(result.getString("COLUMN_KEY"));
                infomation1.setColumnComment(result.getString("COLUMN_COMMENT"));
                fields.add(infomation1);
            }
            infomation.setFiledList(fields);
            tableInfoList.add(infomation);
        }
        return tableInfoList;
    }

    public static void deleteFileOrDirectory(String filePath){
        File file = new File(filePath);
        deleteFileOrDirectory(file);
    }
    public static void deleteFileOrDirectory(File file){
        if(file == null){
            return;
        }
        if(!file.exists()){
            return;
        }
        int i;
        if(file.isFile()){
            boolean delete = file.delete();
            for(i = 0; !delete && i++<10;delete = file.delete()){
                System.gc();
            }
            return;
        }
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files != null){
                for (i = 0; i < files.length; i++) {
                    File subFile = files[i];
                    deleteFileOrDirectory(subFile);
                }
            }
            file.delete();
        }

    }

    public static FileOutConfig getOutConfig(String templatePath, String outPath){
        FileOutConfig fileOutConfig = new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                tableInfo.setConvert(true);
                return MessageFormat.format(outPath,tableInfo.getEntityName());
            }
        };
        return fileOutConfig;
    }

    public static void copyFile(String filePath, String targetPath){
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            inputStream = classPathResource.getInputStream();
            outputStream = new FileOutputStream(targetPath);
            byte[] bytes = new byte[1024];
            int read;
            while((read = inputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, read);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream == null){
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {}
            }
        }
    }

}
